package com.founder.devwork.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.founder.devwork.entity.CommitLog;
import com.founder.devwork.entity.Engineer;
import com.founder.devwork.entity.ImportLog;
import com.founder.devwork.entity.Repository;
import com.founder.devwork.service.CommitLogService;
import com.founder.devwork.service.EngineerService;
import com.founder.devwork.service.ImportLogService;
import com.founder.devwork.service.RepositoryService;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * BaseInfoController 用于提供基础信息查询服务。
 * 提供导入日志、仓库、提交日志和工程师的统计信息。
 */
@RestController
@RequestMapping("/api/baseinfo")
@Slf4j
public class BaseInfoController {

    @Autowired
    private ImportLogService importLogService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private CommitLogService commitLogService;

    @Autowired
    private EngineerService engineerService;

    /**
     * 获取基础信息。
     * @return 基础信息
     */
    @GetMapping("/get-base-info")
    public Map<String, Object> getBaseInfo() {
        Map<String, Object> result = new HashMap<>();

        // 1. 最新完成的导入日期
        LocalDateTime latestEndTime = importLogService
            .lambdaQuery()
            .eq(ImportLog::getStatus, 2)
            .orderByDesc(ImportLog::getEndTime)
            .last("LIMIT 1")
            .oneOpt()
            .map(ImportLog::getEndTime)
            .orElse(null);
        result.put("latestImportDate", latestEndTime);

        // 2. Beijing 和 Chengdu repo 数量
        long beijingCount = repositoryService.lambdaQuery().eq(Repository::getGitInstance, "beijing").count();
        long chengduCount = repositoryService.lambdaQuery().eq(Repository::getGitInstance, "chengdu").count();
        result.put("beijingRepoCount", beijingCount);
        result.put("chengduRepoCount", chengduCount);

        // 3. 有 commit 的 repo 数量
        QueryWrapper<CommitLog> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT repository_id, git_instance");
        List<CommitLog> distinctRepos = commitLogService.list(wrapper);
        int reposWithCommits = distinctRepos.size();
        result.put("reposWithCommits", reposWithCommits);

        // 4. 过去1个月有 commit 的 repo 数量
        QueryWrapper<CommitLog> monthWrapper = new QueryWrapper<>();
        monthWrapper.select("DISTINCT repository_id, git_instance");
        monthWrapper.ge("authored_date", LocalDateTime.now().minusMonths(1));
        List<CommitLog> distinctMonthRepos = commitLogService.list(monthWrapper);
        int reposWithCommitsLastMonth = distinctMonthRepos.size();
        result.put("reposWithCommitsLastMonth", reposWithCommitsLastMonth);

        // 5. 总 commit 数量
        long totalCommits = commitLogService.count();
        result.put("totalCommits", totalCommits);

        // 6. 当前自然月的 commit 数量
        LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        long currentMonthCommits = commitLogService.lambdaQuery().ge(CommitLog::getAuthoredDate, monthStart).count();
        result.put("currentMonthCommits", currentMonthCommits);

        // 7: 前一个自然月的 commit 数量
        LocalDateTime previousMonthStart = monthStart.minusMonths(1);
        long previousMonthCommits = commitLogService.lambdaQuery().ge(CommitLog::getAuthoredDate, previousMonthStart).lt(CommitLog::getAuthoredDate, monthStart).count();
        result.put("previousMonthCommits", previousMonthCommits);

        // 8. Engineer 统计
        long totalEngineers = engineerService.lambdaQuery().ne(Engineer::getDeptId, "T0105").count();
        long backendCount = engineerService.lambdaQuery().eq(Engineer::getRole, "backend").ne(Engineer::getDeptId, "T0105").count();
        long frontendCount = engineerService.lambdaQuery().eq(Engineer::getRole, "frontend").ne(Engineer::getDeptId, "T0105").count();
        result.put("totalEngineers", totalEngineers);
        result.put("backendEngineers", backendCount);
        result.put("frontendEngineers", frontendCount);

        return result;
    }
}
